﻿using DailyNote.AppCode;
using Pabo.Calendar;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SQLite;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace DailyNote
{
    public partial class MainFrm : Form
    {
        private string SelectedNodeCheck;
        private string searchTopNodeText = "查询结果";
        private static readonly string IMPORTANT_TASK_SIGN = "★";
        private static readonly string TASK_COMPLETED_SIGN = "√";
        private static readonly string TASK_FAILED_SIGN = "☠";
        public Mutex mutex;
        private DateTime dateTime;
        public MainFrm()
        {
            CheckForIllegalCrossThreadCalls = false; //非安全
            InitializeComponent();
            this.mutex = new Mutex(false, "LUOMG_SINGLE_INSTANCE_MUTEX");
            if (!this.mutex.WaitOne(0, false))
            {
                this.mutex.Close();
                this.mutex = null;
            }

            if (!SQLiteDBHelper.IsDbExists())
            {
                MessageBox.Show("数据库文件不存在，会导致程序无法正常运行", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }
        private void 内容CToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show(Utils.HelpText, "帮助");
        }
        private void 关于AToolStripMenuItem_Click(object sender, EventArgs e)
        {
            about_frm frm = new about_frm();
            frm.ShowDialog();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            InitFrm();
        }
        public void InitFrm()
        {
            dateTime = DateTime.Now;
            toolStripDate.Text = DateTime.Now.ToLongDateString();
            this.fillTreeNode(dateTime.Year, dateTime.Month);
            monthCalendar1_DayClick(null, new DayClickEventArgs(dateTime.ToShortTimeString(), MouseButtons.Left, 1, 1, 1, 1, Rectangle.Empty));
        }
        private void fillTreeNode(int year, int month)
        {
            string str = string.Concat(new object[] { "select day from note where year=", year, " and month=", month, });
            var reader = SQLiteDBHelper.ExecuteReader(str);
            if (reader.HasRows)
            {
                while (reader.Read())
                {
                    int day = reader.GetInt16(0);
                    DateItem ditem = new DateItem();
                    ditem.BackColor1 = Color.Red;
                    ditem.Date = new DateTime(year, month, day);
                    this.monthCalendar1.Dates.Add(ditem);
                }
            }
        }
        private void monthCalendar1_DayClick(object sender, DayClickEventArgs e)
        {
            this.textBoxNote.Enabled = true;
            dateTime = Convert.ToDateTime(e.Date);
            this.label3.Text = dateTime.ToLongDateString();
            ShowText();
        }
        public void ShowText()
        {
            this.textBoxNote.Text = "";
            this.txtWeeklyDaily.Text = "";
            this.txtMonthlyDaily.Text = "";

            IDailyNote daily = new GDailyNote();
            string context = daily.DayDaily(dateTime);
            if (context.Length > 0)
            {
                this.textBoxNote.Text = context;
            }
            else
            {
                StringBuilder list = new StringBuilder();
                list.AppendLine("当前项目：");
                list.AppendLine("1:今日工作完成情况：");
                list.AppendLine(" 1）......");
                list.AppendLine("2:下一步工作日的工作计划：");
                list.AppendLine(" 1）......");
                list.AppendLine("3：已解决难题");
                list.AppendLine("");
                list.AppendLine("4：需要求助");
                this.textBoxNote.Text = list.ToString();
            }

            context = daily.WeeklyDaily(dateTime);
            this.txtWeeklyDaily.Text = context;

            context = daily.MonthlyDaily(dateTime);
            this.txtMonthlyDaily.Text = context;

            this.txtWeeklyDaily.Enabled = false;
            this.txtMonthlyDaily.Enabled = false;
        }
        private void buttonOK_Click(object sender, EventArgs e)
        {
            save();
        }
        private void buttonDelete_Click(object sender, EventArgs e)
        {
            this.delete();
        }
        private void save()
        {
            if (dateTime == null)
            {
                MessageBox.Show("尚未选择具体日期", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
            else if (this.textBoxNote.Text.Length == 0)
            {
                MessageBox.Show("没有文本，无法写入记录", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
            else
            {
                #region MyRegion
                string str2 = this.textBoxNote.Text.TrimEnd(new char[0]);
                string str = string.Concat(new object[] { "select count(*) from note where year=", dateTime.Year, " and month=", dateTime.Month, " and day=", dateTime.Day });
                if (Convert.ToInt32(SQLiteDBHelper.ExecuteScalar(str)) != 0)
                {
                    str = string.Concat(new object[] { "update note set note='", str2, "' where year=", dateTime.Year, " and month=", dateTime.Month, " and day=", dateTime.Day });
                    SQLiteDBHelper.ExecuteNonQuery(str);
                }
                else
                {
                    str = string.Concat(new object[] { "insert into note(year,month,day,note) values(", dateTime.Year, ",", dateTime.Month, ",", dateTime.Day, ",'", str2, "')" });
                    SQLiteDBHelper.ExecuteNonQuery(str);
                    DateItem ditem = new DateItem();
                    ditem.Date = dateTime;
                    this.monthCalendar1.Dates.Add(ditem);
                }
                #endregion
            }
        }
        private void delete()
        {
            if (dateTime == null)
            {
                MessageBox.Show("尚未选择具体日期", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
            else
            {
                #region MyRegion
                try
                {
                    int year = dateTime.Year;
                    int month = dateTime.Month;
                    int day = dateTime.Day;
                    if ((day != 0) && (MessageBox.Show("确定要删除该条记录?", "信息提示", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk) == DialogResult.Yes))
                    {
                        string str = string.Concat(new object[] { "select count(*) from note where year=", year, " and month=", month, " and day=", day });
                        if (Convert.ToInt32(SQLiteDBHelper.ExecuteScalar(str)) != 0)
                        {
                            str = string.Concat(new object[] { "delete from note where year=", year, " and month=", month, " and day=", day });
                            if (SQLiteDBHelper.ExecuteNonQuery(str) == 0)
                            {
                                MessageBox.Show("删除失败", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                            }
                            else
                            {
                                this.textBoxNote.Clear();
                            }
                        }
                    }
                }
                catch (Exception exception)
                {
                    MessageBox.Show(exception.Message, "出错提示", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                }
                #endregion
            }
        }
        private void buttonSearch_Click(object sender, EventArgs e)
        {
            #region MyRegion
            try
            {
                string[] strArray;
                string text = this.textBoxSearch.Text;
                string str2 = "and";
                if (text.Contains("&&"))
                {
                    str2 = "and";
                    strArray = text.Split(new char[] { '&', '&' });
                }
                else if (text.Contains("||"))
                {
                    str2 = "or";
                    strArray = text.Split(new char[] { '|', '|' });
                }
                else
                {
                    str2 = "and";
                    strArray = text.Split(new char[] { ' ' });
                }
                for (int i = 0; i < strArray.Length; i++)
                {
                    strArray[i] = strArray[i].Trim();
                }
                string str3 = null;
                switch (str2)
                {
                    case "and":
                        if (strArray.Length == 0)
                        {
                            str3 = "select * from note order by year,month,day ASC";
                        }
                        else
                        {
                            int num2 = 0;
                            str3 = "select * from note";
                            for (int j = 0; j < strArray.Length; j++)
                            {
                                if (strArray[j] != "")
                                {
                                    if (num2 == 0)
                                    {
                                        str3 = str3 + " where note like '%" + strArray[j] + "%'";
                                        num2 = 1;
                                    }
                                    else
                                    {
                                        str3 = str3 + " and note like '%" + strArray[j] + "%'";
                                    }
                                }
                            }
                            str3 = str3 + " order by year,month,day ASC";
                        }
                        break;

                    case "or":
                        if (strArray.Length == 0)
                        {
                            str3 = "select * from note order by year,month,day ASC";
                        }
                        else
                        {
                            int num4 = 0;
                            str3 = "select * from note";
                            for (int k = 0; k < strArray.Length; k++)
                            {
                                if (strArray[k] != "")
                                {
                                    if (num4 == 0)
                                    {
                                        str3 = str3 + " where note like '%" + strArray[k] + "%'";
                                        num4 = 1;
                                    }
                                    else
                                    {
                                        str3 = str3 + " or note like '%" + strArray[k] + "%'";
                                    }
                                }
                            }
                            str3 = str3 + " order by year,month,day ASC";
                        }
                        break;
                }
                SQLiteDataReader reader = SQLiteDBHelper.ExecuteReader(str3);
                this.treeViewDay.BeginUpdate();
                this.treeViewDay.Nodes.Clear();
                TreeNode node = new TreeNode(this.searchTopNodeText);
                node.ImageIndex = 0;
                node.Tag = new DateTime();
                node.ImageIndex = 0;
                node.SelectedImageIndex = 0;
                this.treeViewDay.Nodes.Add(node);
                while (reader.Read())
                {
                    TreeNode node2 = new TreeNode(string.Concat(new object[] { reader["year"].ToString(), "年", reader["month"].ToString(), "月", reader["day"], "日" }));
                    node2.Tag = new DateTime(Convert.ToInt32(reader["year"]), Convert.ToInt32(reader["month"]), Convert.ToInt32(reader["day"]));
                    node2.ImageIndex = 2;
                    node2.SelectedImageIndex = 2;
                    this.treeViewDay.TopNode.Nodes.Add(node2);
                }
                this.treeViewDay.ExpandAll();
                this.treeViewDay.EndUpdate();
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message, "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
            #endregion
        }
        private void treeViewDay_AfterSelect(object sender, TreeViewEventArgs e)
        {
            #region MyRegion
            try
            {
                SelectedNodeCheck = this.treeViewDay.SelectedNode.Text;
                string text = this.textBoxNote.Text;
                string str = string.Concat(new object[] { "select note from note where year=", dateTime.Year, " and month=", dateTime.Month, " and day=", dateTime.Day });
                SQLiteDataReader reader = SQLiteDBHelper.ExecuteReader(str);
                reader.Read();
                this.textBoxNote.Text = reader["note"].ToString();
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message, "出错提示", MessageBoxButtons.OK, MessageBoxIcon.Hand);
            }
            #endregion
        }
        private void textBoxNote_KeyDown(object sender, KeyEventArgs e)
        {
            if ((!e.Alt && !e.Control) && (e.KeyCode == Keys.Delete))
            {
                this.delete();
            }
        }
        private void numericUpDownYear_ValueChanged(object sender, EventArgs e)
        {
            int year = (int)this.numericUpDownYear.Value;
            int month = (int)this.numericUpDownMonth.Value;
            this.fillTreeNode(year, month);
        }
        private void numericUpDownMonth_ValueChanged(object sender, EventArgs e)
        {
            int year = (int)this.numericUpDownYear.Value;
            int month = (int)this.numericUpDownMonth.Value;
            this.fillTreeNode(year, month);
        }
        private void textBoxNote_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
        {
            #region MyRegion
            if (e.KeyCode == Keys.F1)
            {
                textBoxNote.SelectionLength = 0;
                textBoxNote.SelectedText = TASK_COMPLETED_SIGN + " " + DateTime.Now.ToShortTimeString() + ".";
                textBoxNote.Focus();
            }
            else if (e.KeyCode == Keys.F2)
            {
                textBoxNote.SelectionLength = 0;
                textBoxNote.SelectedText = IMPORTANT_TASK_SIGN + ".";
                textBoxNote.Focus();
            }
            else if (e.KeyCode == Keys.F3)
            {
                textBoxNote.SelectionLength = 0;
                textBoxNote.SelectedText = IMPORTANT_TASK_SIGN + IMPORTANT_TASK_SIGN + ".";
                textBoxNote.Focus();
            }
            else if (e.KeyCode == Keys.F4)
            {
                textBoxNote.SelectionLength = 0;
                textBoxNote.SelectedText = IMPORTANT_TASK_SIGN + IMPORTANT_TASK_SIGN + IMPORTANT_TASK_SIGN + ".";
                textBoxNote.Focus();
            }
            else if (e.KeyCode == Keys.F5)
            {
                textBoxNote.SelectionLength = 0;
                textBoxNote.SelectedText = TASK_FAILED_SIGN + ".";
                textBoxNote.Focus();
            }
            else if (e.KeyCode == Keys.F10)
            {
                AutoStart.SetSelfStartup();
            }
            else if (e.KeyCode == Keys.F12)
            {
                MessageBox.Show(Utils.HelpText, "帮助");
            }
            else if ((!e.Alt && e.Control) && (e.KeyCode == Keys.S))
            {
                this.save();
            }
            #endregion
        }

        private void 发送日报ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                string smd = dateTime.ToString("MM-dd");
                string title = "罗敏贵/" + smd;

                IDailyNote daily = new GDailyNote();
                string context = daily.DayDaily(dateTime);

                SenderMail(title, context);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void 发送周报ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DateTime ben = DateTime.Now.AddDays(Convert.ToDouble((0 - Convert.ToInt16(dateTime.DayOfWeek))));
            DateTime end = DateTime.Now.AddDays(Convert.ToDouble((6 - Convert.ToInt16(dateTime.DayOfWeek))));
            string title = Utils.Author + "_周报_" + ben.ToLongDateString() + "---" + end.ToLongDateString();

            IDailyNote daily = new GDailyNote();
            string context = daily.MonthlyDaily(dateTime);

            SenderMail(title, context);
        }

        private void 发送月报ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string smd = dateTime.ToString("MM-dd");
            string title = Utils.Author + "_月报_" + dateTime.ToString("YY/MM");

            IDailyNote daily = new GDailyNote();
            string context = daily.MonthlyDaily(dateTime);

            SenderMail(title, context);
        }

        public void SenderMail(string title, string context)
        {
            if (context.Length > 0)
            {
                bool flg = MailHelper.SendMail(title, context, "luomg@firecn.net", "123456", new List<string> { "yugen@firecn.net","minguiluo@163.com" }, "smtp.ym.163.com");
                if (flg)
                    MessageBox.Show("发送邮件成功！！！");
                else
                    MessageBox.Show("发送邮件失败！！！");
            }
        }
    }
}
